package com.kitty.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.kitty.common.start.GameData;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.artifact.ArtifactService;
import com.kitty.game.mail.model.Mail;
import com.kitty.game.notice.model.Notice;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.model.PetBox;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.JsonUtils;
import com.kitty.game.utils.StringUtil;
import com.kitty.game.utils.TimeUtil;
import com.kitty.mina.cache.DataCache;
import com.kitty.web.controller.BaseController;
import com.kitty.web.common.AjaxResult;
import com.kitty.web.core.page.TableDataInfo;

import com.kitty.web.domain.ClearDaoVo;
import com.kitty.web.domain.ReqRole;
import com.kitty.web.domain.TAccount;
import com.kitty.web.domain.TRole;
import com.kitty.web.system.account.service.ITAccountServiceM;
import com.kitty.web.system.accountrole.service.ITRoleService;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.xml.stream.events.Characters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 角色管理Controller
 *
 * @author soul
 * @date 2022-04-22
 */
@Controller
@RequestMapping("/system/accountrole")
@Slf4j
public class TRoleController extends BaseController
{
    private String prefix = "system/accountrole";

    @Autowired
    private ITRoleService tRoleService;
    @Autowired
    private ITAccountServiceM itAccountServiceM;


    @GetMapping()
    public String role()
    {
        return prefix + "/accountrole";
    }


    /**
     * 清除角色道行
     */
    public AjaxResult clearRoleDao(ClearDaoVo clearDaoVo){
        int reserveDao = Integer.parseInt(clearDaoVo.getReserveDao() )* 360;
        List<TRole> tRoles = tRoleService.selectTRoleList(new TRole());
        log.info("预处理总数："+tRoles.size());
        int roleNum = 0;
        for (TRole tRole : tRoles) {
            try {
                Long taopoint = tRole.getTaopoint()/ Const.ONE_DAY_POINT;
                if(taopoint>reserveDao){
                    log.info("角色："+tRole.getName()+"     道行："+taopoint);
                    int num =  (taopoint.intValue()-reserveDao)/ (Integer.parseInt(clearDaoVo.getLimit()) * Const.ONE_YEAR_DAY);
                    Mail mail = SpringUtils.getMailService().createMail("清理道行补偿", "清理道行补偿", 7 * TimeUtil.ONE_DAY);
                    ArrayList<NutMap> maps = new ArrayList<>();
                    for (int i = 0; i < num; i++) {
                        maps.add(new NutMap().setv("data", "#I物品|" + clearDaoVo.getItemName() + "#r" + clearDaoVo.getItemNum() + "#I").setv("type", Const.rewardWupin));
                    }
                    mail.getDatas().addAll(maps);
                    Role role = SpringUtils.getRoleService().getPlayerBy(tRole.getUid());
                    role.setTaoPoint((long)reserveDao * Const.ONE_DAY_POINT);
                    SpringUtils.getMailService().sendNewMail(role, mail);
                    roleNum +=1;
                }
            } catch (Exception e) {
                log.info("角色："+tRole.getName()+"初始化道行出错!");
            }
        }
        log.info("实际处理总数："+roleNum);
        return AjaxResult.success();
    }
    /**
     * 清除宠物武学
     */

    public AjaxResult clearPetWu(ClearDaoVo clearDaoVo){
        int reserveWu = Integer.parseInt(clearDaoVo.getReserveWu());
        List<TRole> tRoles = tRoleService.selectTRoleList(new TRole());
        log.info("预处理总数："+tRoles.size());
        int roleNum = 0;
        for (TRole tRole : tRoles) {
            try {
                Role role = SpringUtils.getRoleService().getPlayerBy(tRole.getUid());
                PetBox petBox = role.getPetBox();
                Map<Integer, Pet> allPets = petBox.getAllPets();
                Mail mail = SpringUtils.getMailService().createMail("清理武学补偿", "清理武学补偿", 7 * TimeUtil.ONE_DAY);
                ArrayList<NutMap> maps = new ArrayList<>();
                int petNum = 0;
                for (Map.Entry<Integer, Pet> integerPetEntry : allPets.entrySet()) {
                    Pet pet = integerPetEntry.getValue();
                    int martial = pet.getMartial();
                    log.info("角色："+tRole.getName()+"     宠物："+pet.getName()+"   武学："+martial);
                    if(martial>reserveWu){
                        if(!StringUtil.isEmpty(clearDaoVo.getItemName())){
                            int num =  (martial-reserveWu)/Integer.parseInt(clearDaoVo.getLimit());
                            for (int i = 0; i < num; i++) {
                                maps.add(new NutMap().setv("data", "#I物品|" + clearDaoVo.getItemName() + "#r" + clearDaoVo.getItemNum() + "#I").setv("type", Const.rewardWupin));
                            }
                        }
                        pet.setMartial(reserveWu);
                    }
                    petNum+=1;

                }
                log.info("角色："+tRole.getName()+"处理宠物武学数量："+petNum);
                if(petNum > 0 ){
                    mail.getDatas().addAll(maps);
                    petBox.setAllPets(allPets);
                    role.setPetBox(petBox);
                    if(StringUtil.isEmpty(clearDaoVo.getItemName())){
                        role.save();
                    }else{
                        SpringUtils.getMailService().sendNewMail(role, mail);
                    }
                    roleNum +=1;
                }
            } catch (Exception e) {
                log.info("角色："+tRole.getName()+"初始化武学出错!");
            }
        }
        log.info("实际处理总数："+roleNum);
        return AjaxResult.success();

    }


    /**
     * 查询角色管理列表
     */

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TRole tRole)
    {

        startPage();
        List<TRole> list = tRoleService.selectTRoleList(tRole);
        for (TRole role : list) {
            if(role.getOnLine() == 1){
                if(DataCache.ONLINE_ROLES.containsKey(role.getUid())){
                    role.setOnLine(1L);
                }else{
                    role.setOnLine(0L);
                }
            }else{
                role.setOnLine(0L);
            }

        }
        return getDataTable(list);
    }
    @PostMapping("/countOnline")
    @ResponseBody
    public AjaxResult getOnlineCount(){
        int neice = ServerService.neice;
        int gate = ServerService.gate;
        Map map = new HashMap<>();
        map.put("neice", neice);
        map.put("gate",gate);
        map.put("onlineRoles",DataCache.ONLINE_ROLES.size());
        AjaxResult ajaxResult = new AjaxResult(AjaxResult.Type.SUCCESS,"",map );
        return ajaxResult;
    }
    @Autowired
    Dao dao;
    @PostMapping("/findGongGao")
    @ResponseBody
    public AjaxResult getGongGao(){
        List<Notice> query = dao.query(Notice.class, Cnd.NEW());

        String content = query.get(0).getContent();
        Map map = new HashMap<>();

        map.put("content",content);
        AjaxResult ajaxResult = new AjaxResult(AjaxResult.Type.SUCCESS,"",map );
        return ajaxResult;
    }
    @Autowired
    RoleService roleService;

    @PostMapping("/getRolexy")
    @ResponseBody
    public AjaxResult getRoleXy(String name){
        Role role = roleService.getOnlinePlayer(name);
        if(role == null){
            AjaxResult ajaxResult = new AjaxResult(AjaxResult.Type.ERROR,"不在线","" );
            return ajaxResult;
        }


        Map map = new HashMap<>();

        map.put("x", role.getPos().getX());
        map.put("y", role.getPos().getY());
        AjaxResult ajaxResult = new AjaxResult(AjaxResult.Type.SUCCESS,"",map );
        return ajaxResult;
    }

    @PostMapping("/findgjc")
    @ResponseBody
    public AjaxResult findgjc(){
        String joinTeamKey = DataCache.REDIS_DATA.get("joinTeamKey");
        Map map = new HashMap<>();
        map.put("content",joinTeamKey);
        AjaxResult ajaxResult = new AjaxResult(AjaxResult.Type.SUCCESS,"",map );
        return ajaxResult;
    }

    @PostMapping("/currentServer")
    @ResponseBody
    public AjaxResult getCurrentServer(){

        String server =  SpringUtils.getBean(ServerService.class).getServer().getSonName();
        AjaxResult ajaxResult = new AjaxResult(AjaxResult.Type.SUCCESS,"",server);
        return ajaxResult;
    }
    @PostMapping("/queryAccount")
    @ResponseBody
    public AjaxResult queryAccount(ReqRole reqRole){
        String sid = reqRole.getRoleId();
        TAccount tAccount = itAccountServiceM.selectTAccountById(sid);
        AjaxResult ajaxResult = new AjaxResult(AjaxResult.Type.SUCCESS,"",tAccount.getUsername());
        return ajaxResult;
    }



    /**
     * 新增角色管理
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存角色管理
     */

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TRole tRole)
    {
        return toAjax(tRoleService.insertTRole(tRole));
    }

    /**
     * 修改角色管理
     */
    @GetMapping("/edit/{roleid}")
    public String edit(@PathVariable("roleid") Long roleid, ModelMap mmap)
    {
        TRole tRole = tRoleService.selectTRoleById(roleid);
        mmap.put("tRole", tRole);
        return prefix + "/edit";
    }

    /**
     * 修改保存角色管理
     */

    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TRole tRole)
    {
        return toAjax(tRoleService.updateTRole(tRole));
    }

    /**
     * 删除角色管理
     */

    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(tRoleService.deleteTRoleByIds(ids));
    }
}
